import cv2
import numpy as np
import os


def contrast(img0):   
    img1 = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY) #彩色转为灰度图片
    m, n = img1.shape
    #图片矩阵向外扩展一个像素
    img1_ext = cv2.copyMakeBorder(img1,1,1,1,1,cv2.BORDER_REPLICATE) 
    rows_ext,cols_ext = img1_ext.shape
    
                    
    b = 0.0
    for i in range(1,rows_ext-1):
        for j in range(1,cols_ext-1):
            b += ((img1_ext[i,j]-img1_ext[i,j+1])**2 + (img1_ext[i,j]-img1_ext[i,j-1])**2 + 
                    (img1_ext[i,j]-img1_ext[i+1,j])**2 + (img1_ext[i,j]-img1_ext[i-1,j])**2)

    cg = b/(4*(m-2)*(n-2)+3*(2*(m-2)+2*(n-2))+2*4) #对应上面48的计算公式
    print(cg)
    return cg


#批量读取
list=[]
length=len(os.listdir("image\\2F"))
x=[]
#读入图片地址
for i in range(length):
    list.append("image\\2F\\{}.jpg".format(str(i+1))) 

#对读入的图片批量操作
for j in range(length):
    image=cv2.imread(list[j])
    x.append(contrast(image))
print(x)
